import L from 'leaflet'
interface AreaNameConfig {
  lat: number
  lng: number
  name: string
  // children: AreaNameConfig[]
}

interface PointConfig {
  lat: number
  lng: number
  pointId: number
  // name: string
  // icon: string
}

interface Vector {
  x: number
  y: number
}

export class MapManager {
  private map: L.Map
  private areaNameLayerGroup: L.LayerGroup | undefined
  private pointLayerGroup: L.LayerGroup | undefined
  private mapAnchorList: AreaNameConfig[] = []
  private prevZoom = 0
  private lastActivePointId = -1
  private pointList: PointConfig[] = []

  constructor(domId: string) {
    const bounds = L.latLngBounds(L.latLng(0, 0), L.latLng(-256, 256)) // 边界

    this.map = L.map(domId, {
      maxBounds: bounds,
      center: [-102, 148],
      crs: L.CRS.Simple,
      zoomControl: false,
      attributionControl: false,
      maxZoom: 7,
      minZoom: 4,
      zoom: 5
    })
    L.tileLayer('images/map/{z}/{x}/{y}.png', {
      minZoom: 4,
      maxZoom: 7,
      bounds,
      noWrap: true
    }).addTo(this.map)
    console.log('init', this.map)
  }

  renderAreaNames(configList: AreaNameConfig[]) {
    const markers = configList.map(this.getAreaNameMarkerItem)
    this.areaNameLayerGroup = L.layerGroup(markers)
    this.areaNameLayerGroup.addTo(this.map)
  }

  renderPoints(pointList: PointConfig[]) {
    const pointerMarkers = pointList.map((val: any) => {
      const { lat, lng, pointId } = val
      const iconUrl = `images/map-icon/${pointId}.png`
      const marker = L.marker([lat, lng], {
        icon: L.divIcon({
          className: 'map-point-item',
          html: `<div class="point-item-container">
          <div class="point-pic" style="background-image: url(${iconUrl})"></div>
          </div>`
        })
      })
      return marker
    })
    this.pointLayerGroup = L.layerGroup(pointerMarkers)
    this.pointLayerGroup.addTo(this.map)
  }

  getAreaNameMarkerItem(config: AreaNameConfig) {
    const { lat = 0, lng = 0, name } = config
    return L.marker([lat, lng], {
      icon: L.divIcon({
        className: 'map-mark-item',
        html: `<div class="area-mark-item">${name}</div>`
      })
    })
  }

  enableClickDebug() {
    this.map.on('click', (wl: any) => {
      const cordinate = wl.latlng
      console.log('cordinate', cordinate)
    })
  }
}
